package com.example.easybuy.service.impl;

import com.example.easybuy.entity.Car;
import com.example.easybuy.entity.CarDetail;
import com.example.easybuy.service.CarService;
import com.example.easybuy.util.AjaxResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CarServiceImpl implements CarService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public AjaxResult addCar(Map<String, Object> map) {
        CarDetail carDetail = new CarDetail();
        Car car = new Car();
        Map<String, CarDetail> map1 = new HashMap<>();
        if (map.containsKey("productId") && !map.get("productId").toString().isEmpty()) {
            carDetail.setProductId(Integer.parseInt(map.get("productId").toString()));
        }
        if (map.containsKey("stock") && !map.get("stock").toString().isEmpty()) {
            carDetail.setStock(Integer.parseInt(map.get("stock").toString()));
        }
        if (map.containsKey("productName") && !map.get("productName").toString().isEmpty()) {
            carDetail.setProductName(map.get("productName").toString());
        }
        //唯一标识
        if (map.containsKey("loginName") && !map.get("loginName").toString().isEmpty()) {
            car.setId(map.get("loginName").toString() + "-car");
        }
        if (map.containsKey("fileName") && !map.get("fileName").toString().isEmpty()) {
            carDetail.setFileName(map.get("fileName").toString());
        }
        if (map.containsKey("totalNum") && !map.get("totalNum").toString().isEmpty()) {
            carDetail.setTotalNum(Integer.parseInt(map.get("totalNum").toString()));
        } else {
            carDetail.setTotalNum(1);
        }
        if (map.containsKey("price") && !map.get("price").toString().isEmpty()) {
            carDetail.setPrice(Double.parseDouble(map.get("price").toString()));
            carDetail.setTotalPrice(carDetail.getPrice() * carDetail.getTotalNum());//精度处理
        }
        if (stringRedisTemplate.opsForValue().get(car.getId()) != null) {
            ObjectMapper objectMapper = new ObjectMapper();
            String carJson = stringRedisTemplate.opsForValue().get(car.getId());
            Car oldCar = null;
            try {
                oldCar = objectMapper.readValue(carJson, Car.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            map1 = oldCar.getProductMap();
        }

        if (map1.containsKey(carDetail.getProductId() + "")) {
            CarDetail hasCardetail = map1.get(carDetail.getProductId() + "");
            hasCardetail.setTotalNum(hasCardetail.getTotalNum() + carDetail.getTotalNum());
            hasCardetail.setTotalPrice(hasCardetail.getTotalPrice() + carDetail.getTotalPrice());
            map1.put(carDetail.getProductId() + "", hasCardetail);
        } else {
            map1.put(carDetail.getProductId() + "", carDetail);
        }
        car.setProductMap(map1);

        double totalPrice = 0;
        int totalNum = 0;
        for (Map.Entry<String, CarDetail> entry : car.getProductMap().entrySet()) {
            System.out.println(entry.getValue());
            totalPrice = totalPrice + entry.getValue().getTotalPrice();
            totalNum = totalNum + entry.getValue().getTotalNum();
        }
        car.setTotalPrice(totalPrice);
        car.setTotalNum(totalNum);
        ObjectMapper objectMapper = new ObjectMapper();
        String carJson = "";
        try {
            carJson = objectMapper.writeValueAsString(car);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        stringRedisTemplate.opsForValue().set(car.getId(), carJson);

        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateCar(List<CarDetail> cars, String loginName) {
        if (stringRedisTemplate.opsForValue().get(loginName + "-car") == null) {
            return AjaxResult.error().add("msg", "暂无购物车!");
        }
        Map<String, CarDetail> map = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        String carJson = stringRedisTemplate.opsForValue().get(loginName + "-car");
        Car oldCar = null;
        try {
            oldCar = objectMapper.readValue(carJson, Car.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        map = oldCar.getProductMap();
        for (CarDetail carDetail : cars) {
            if (map.containsKey(carDetail.getProductId() + "")) {
                map.put(carDetail.getProductId() + "", carDetail);
            }
        }
        Car car = new Car();
        car.setId(loginName + "-car");
        car.setProductMap(map);
        double totalPrice = 0;
        int totalNum = 0;
        for (Map.Entry<String, CarDetail> entry : car.getProductMap().entrySet()) {
            System.out.println(entry.getValue());
            totalPrice = totalPrice + entry.getValue().getTotalPrice();
            totalNum = totalNum + entry.getValue().getTotalNum();
        }
        car.setTotalPrice(totalPrice);
        car.setTotalNum(totalNum);
        String newCarJson = "";
        try {
            newCarJson = objectMapper.writeValueAsString(car);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        stringRedisTemplate.opsForValue().set(car.getId(), newCarJson);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult delCar(String loginName, Integer productId) {//接收多个productId,Integer...
        Car car = this.getCar(loginName);
        Map<String, CarDetail> map = car.getProductMap();
        map.remove(productId + "");
        Car newCar = new Car();
        newCar.setId(loginName + "-car");
        newCar.setProductMap(map);
        double totalPrice = 0;
        int totalNum = 0;
        for (Map.Entry<String, CarDetail> entry : newCar.getProductMap().entrySet()) {
            System.out.println(entry.getValue());
            totalPrice = totalPrice + entry.getValue().getTotalPrice();
            totalNum = totalNum + entry.getValue().getTotalNum();
        }
        newCar.setTotalPrice(totalPrice);
        newCar.setTotalNum(totalNum);
        String newCarJson = "";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            newCarJson = objectMapper.writeValueAsString(newCar);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        stringRedisTemplate.opsForValue().set(newCar.getId(), newCarJson);
        return AjaxResult.success();
    }

    @Override
    public Car getCar(String loginName) {
        String key = loginName + "-car";
        ObjectMapper objectMapper = new ObjectMapper();
        String carJson = stringRedisTemplate.opsForValue().get(key);
        Car car = new Car();
        if (stringRedisTemplate.opsForValue().get(key) != null) {
            try {
                car = objectMapper.readValue(carJson, Car.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return car;
    }
}
